<template>
  <div class="min-h-screen bg-blue-50">
    <!-- 页面头部 -->
    <header class="border-b border-gray-200 relative overflow-hidden py-16 bg-gradient-to-r from-blue-50 to-purple-50">
      <!-- 弹幕系统 -->
      <BarrageSystem 
        :stats-data="{
          total: upcomingContests.length + (currentContest ? 1 : 0),
          solved: recentRankings.length,
          rate: 85.6,
          submissions: 0
        }"
        :custom-barrage-data="contestBarrageData"
        @tag-click="handleTagClick"
      />

      <!-- 主要内容层 -->
      <div class="container mx-auto px-4 py-4 sm:py-6 lg:py-8 relative z-10">
        <div class="text-center">
          <div class="inline-flex items-center justify-center w-12 h-12 sm:w-16 sm:h-16 bg-gradient-to-r from-yellow-500 to-orange-500 rounded-full mb-3 sm:mb-4 shadow-lg">
            <svg class="w-6 h-6 sm:w-8 sm:h-8 text-white" fill="currentColor" viewBox="0 0 24 24">
              <path d="M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"/>
            </svg>
          </div>
          <h1 class="text-4xl font-extrabold leading-tight tracking-tight bg-gradient-to-r from-yellow-600 via-orange-500 to-red-500 bg-clip-text text-transparent">算法竞赛</h1>
          <p class="text-gray-500 mt-2 text-base leading-relaxed">快来参加每周排位赛，提升你的世界排名</p>
        </div>
      </div>
    </header>

    <!-- 主要内容区域 -->
    <div class="container mx-auto px-4 py-6 sm:py-8">
      <div class="grid grid-cols-1 lg:grid-cols-12 gap-6 sm:gap-8">
        <!-- 左侧：竞赛预告侧边栏 -->
        <div class="lg:col-span-3">
          <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="p-4 border-b border-gray-200">
              <h3 class="text-lg font-semibold text-gray-900">竞赛预告</h3>
            </div>
            <div class="p-4">
              <div v-if="upcomingContests.length === 0" class="text-center py-8 text-gray-500">
                <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <p>暂无即将开始的竞赛</p>
              </div>
              <div v-else class="space-y-3">
                <div v-for="contest in upcomingContests" :key="contest.id" 
                     class="p-3 bg-white border border-gray-200 rounded-lg shadow-sm hover:border-blue-300 hover:bg-blue-50 transition-colors transition-shadow hover:shadow-md cursor-pointer"
                     @click="$router.push(`/contests/${contest.id}`)">
                  <div class="flex items-center justify-between mb-2">
                    <h4 class="font-medium text-gray-900">{{ contest.title }}</h4>
                    <span class="text-xs font-medium text-gray-700 bg-gray-100 px-2 py-0.5 rounded-full">{{ contest.type }}</span>
                  </div>
                  <p class="text-sm text-gray-600 mb-2">{{ contest.description }}</p>
                  <div class="flex items-center justify-between text-xs text-gray-500">
                    <span>{{ formatDateTime(contest.start_time) }}</span>
                    <span>{{ contest.duration }}分钟</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 中间：当前竞赛和排行榜 -->
        <div class="lg:col-span-6">
          <!-- 当前竞赛 -->
          <div class="mb-8">
            <div v-if="currentContest" class="bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg shadow-lg overflow-hidden">
              <div class="p-6 text-white">
                <div class="flex items-center justify-between mb-4">
                  <div>
                    <h2 class="text-2xl font-bold mb-2">{{ currentContest.title }}</h2>
                    <p class="text-blue-100">{{ currentContest.description }}</p>
                  </div>
                  <div class="text-right">
                    <div class="text-2xl font-bold">{{ getTimeUntilStart(currentContest.start_time) }}</div>
                    <div class="text-blue-100 text-sm">距离开始</div>
                  </div>
                </div>
                
                <div class="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm mb-4">
                  <div class="flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    {{ currentContest.duration }} 分钟
                  </div>
                  <div class="flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"></path>
                    </svg>
                    {{ currentContest.participant_count }} 人报名
                  </div>
                  <div class="flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                    </svg>
                    {{ currentContest.questions?.length || 0 }} 道题
                  </div>
                  <div class="flex items-center">
                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"></path>
                    </svg>
                    {{ currentContest.type }}
                  </div>
                </div>
                
                <div class="flex gap-3">
                  <button
                    @click="joinContest(currentContest.id)"
                    class="flex-1 bg-white text-blue-600 font-bold py-2 px-4 rounded-lg hover:bg-blue-50 transition-colors"
                  >
                    立即报名
                  </button>
                  <button
                    @click="$router.push(`/contests/${currentContest.id}`)"
                    class="px-4 py-2 border border-white text-white font-bold rounded-lg hover:bg-white hover:text-blue-600 transition-colors"
                  >
                    查看详情
                  </button>
                </div>
              </div>
            </div>
            
            <!-- 无当前竞赛提示 -->
            <div v-else class="bg-white rounded-lg shadow-sm border border-gray-200 p-8 text-center">
              <div class="flex flex-col items-center">
                <svg class="w-16 h-16 text-gray-300 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <h3 class="text-lg font-semibold text-gray-900 mb-2">暂无当前竞赛</h3>
                <p class="text-gray-500 mb-4">目前没有正在进行的竞赛，请关注即将开始的竞赛</p>
                <button 
                  @click="refreshContests"
                  :disabled="loading"
                  :class="[
                    'px-4 py-2 rounded-lg transition-colors flex items-center gap-2',
                    loading 
                      ? 'bg-gray-400 text-gray-200 cursor-not-allowed' 
                      : 'bg-blue-600 text-white hover:bg-blue-700'
                  ]"
                >
                  <svg v-if="loading" class="w-4 h-4 animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                  </svg>
                  <svg v-else class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
                  </svg>
                  {{ loading ? '刷新中...' : '刷新竞赛列表' }}
                </button>
              </div>
            </div>
          </div>

        </div>

        <!-- 右侧：历史竞赛 -->
        <div class="lg:col-span-3">
          <div class="bg-white rounded-lg shadow-sm border border-gray-200">
            <div class="p-4 border-b border-gray-200">
              <h3 class="text-lg font-semibold text-gray-900">往届竞赛回顾</h3>
              <p class="text-sm text-gray-600 mt-1">参加虚拟竞赛，为排位赛做好充足准备</p>
            </div>
            <div class="p-4">
              <div v-if="historyContests.length === 0" class="text-center py-8 text-gray-500">
                <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
                </svg>
                <p>暂无历史竞赛</p>
              </div>
              <div v-else class="space-y-3">
                <div v-for="contest in historyContests" :key="contest.id" 
                     class="p-3 bg-white border border-gray-200 rounded-lg shadow-sm hover:border-blue-300 hover:bg-blue-50 transition-colors transition-shadow hover:shadow-md cursor-pointer"
                     @click="$router.push(`/contests/${contest.id}`)">
                  <div class="flex items-center justify-between mb-2">
                    <h4 class="font-medium text-gray-900">{{ contest.title }}</h4>
                    <span class="text-xs font-medium text-gray-700 bg-gray-100 px-2 py-0.5 rounded-full">{{ contest.type }}</span>
                  </div>
                  <p class="text-sm text-gray-600 mb-2">{{ contest.description }}</p>
                  <div class="flex items-center justify-between text-xs text-gray-500">
                    <span>{{ formatDate(contest.end_time) }}</span>
                    <span>{{ contest.participant_count }}人参与</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 排名部分 - 全宽显示 -->
      <div class="mt-8">
        <div class="bg-white rounded-lg shadow-sm border border-gray-200">
          <div class="p-4 border-b border-gray-200">
            <div class="flex items-center justify-between">
              <h3 class="text-lg font-semibold text-gray-900">排名</h3>
              <div class="flex items-center bg-gray-100 rounded-md overflow-hidden text-sm">
                <button
                  :class="['px-3 py-1', !showGlobal ? 'bg-white text-gray-900' : 'text-gray-600']"
                  @click="showGlobal = false"
                >校内</button>
                <button
                  :class="['px-3 py-1', showGlobal ? 'bg-white text-gray-900' : 'text-gray-600']"
                  @click="showGlobal = true"
                >全球</button>
              </div>
            </div>
          </div>
          <div class="p-4">
            <div v-if="recentRankings.length === 0" class="text-center py-8 text-gray-500">
              <svg class="w-12 h-12 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"></path>
              </svg>
              <p>暂无竞赛数据</p>
            </div>
            <div v-else class="space-y-4">
              <div v-for="(ranking, index) in (Array.isArray(recentRankings) ? recentRankings.filter(r => r) : [])" :key="ranking?.contest?.id || index" class="border border-gray-200 rounded-lg p-4">
                <div class="flex items-center justify-between mb-3">
                  <h4 class="font-medium text-gray-900">{{ ranking?.contest?.title || '未知竞赛' }}</h4>
                  <span class="text-xs text-gray-500">{{ formatDate(ranking?.contest?.end_time) }}</span>
                </div>
                
                <div class="space-y-2">
                  <div v-for="(participant, index) in (ranking?.top_rankings || []).slice(0, 3)" :key="participant.id" 
                       class="flex items-center justify-between text-sm">
                    <div class="flex items-center gap-2">
                      <span :class="[
                        'w-5 h-5 rounded-full flex items-center justify-center text-xs font-bold',
                        index === 0 ? 'bg-yellow-100 text-yellow-800' :
                        index === 1 ? 'bg-gray-100 text-gray-600' :
                        'bg-orange-100 text-orange-600'
                      ]">
                        {{ index + 1 }}
                      </span>
                      <span class="text-gray-700">{{ participant.user?.username || '匿名用户' }}</span>
                    </div>
                    <span class="text-gray-500">{{ participant.total_score }}分</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import BarrageSystem from '@/components/Common/BarrageSystem.vue'
import { 
  getUpcomingContests, 
  getCurrentContest, 
  getRecentContestRankings,
  joinContest as joinContestAPI,
  type Contest,
  type RecentContestRanking
} from '@/api/contest'

const router = useRouter()
const authStore = useAuthStore()

// 竞赛弹幕数据
const contestBarrageData = [
  // 统计信息
  { type: 'stats' as const, text: '总竞赛', value: 'total', color: 'purple' },
  { type: 'stats' as const, text: '进行中', value: 'ongoing', color: 'green' },
  { type: 'stats' as const, text: '即将开始', value: 'upcoming', color: 'blue' },
  { type: 'stats' as const, text: '已结束', value: 'finished', color: 'gray' },
  // 竞赛相关标签
  { type: 'tag' as const, text: '算法竞赛', tag: 'algorithm' },
  { type: 'tag' as const, text: '编程竞赛', tag: 'programming' },
  { type: 'tag' as const, text: '数据结构', tag: 'data-structure' },
  { type: 'tag' as const, text: '动态规划', tag: 'dynamic-programming' },
  { type: 'tag' as const, text: '图论', tag: 'graph' },
  { type: 'tag' as const, text: '贪心算法', tag: 'greedy' },
  { type: 'tag' as const, text: '回溯算法', tag: 'backtracking' },
  { type: 'tag' as const, text: '分治算法', tag: 'divide-conquer' },
  { type: 'tag' as const, text: '排序算法', tag: 'sorting' },
  { type: 'tag' as const, text: '搜索算法', tag: 'search' },
  { type: 'tag' as const, text: '数学竞赛', tag: 'math' },
  { type: 'tag' as const, text: '字符串', tag: 'string' },
  { type: 'tag' as const, text: '数论', tag: 'number-theory' },
  { type: 'tag' as const, text: '几何', tag: 'geometry' },
  { type: 'tag' as const, text: '组合数学', tag: 'combinatorics' },
  { type: 'tag' as const, text: '概率论', tag: 'probability' },
  { type: 'tag' as const, text: '挑战自我', tag: 'challenge' },
  { type: 'tag' as const, text: '提升技能', tag: 'skill' },
  { type: 'tag' as const, text: '团队合作', tag: 'teamwork' },
  { type: 'tag' as const, text: '创新思维', tag: 'innovation' }
]

// 统计数据计算属性 - 将在computed属性定义后重新定义

// 处理弹幕标签点击
const handleTagClick = (tag: string) => {
  if (tag === 'algorithm' || tag === 'programming') {
    // 可以跳转到相关页面或执行其他操作
    console.log('点击了算法相关标签:', tag)
  } else if (tag === 'challenge' || tag === 'skill') {
    // 可以跳转到相关页面或执行其他操作
    console.log('点击了挑战相关标签:', tag)
  }
}

// 响应式数据
const upcomingContests = ref<Contest[]>([])
const currentContest = ref<Contest | null>(null)
const historyContests = ref<Contest[]>([])
const recentRankings = ref<RecentContestRanking[]>([])
const showGlobal = ref(false)
const loading = ref(false)

// 加载数据的方法
const loadUpcomingContests = async () => {
  try {
    const response = await getUpcomingContests()
    // 确保返回的数据是数组
    if (Array.isArray(response.data)) {
      upcomingContests.value = response.data
    } else {
      upcomingContests.value = []
    }
  } catch (error) {
    console.error('加载即将开始的竞赛失败:', error)
    upcomingContests.value = []
  }
}

const loadCurrentContest = async () => {
  try {
    const response = await getCurrentContest()
    // 检查返回的数据是否为有效的竞赛对象
    if (response.data && typeof response.data === 'object' && response.data.id) {
      currentContest.value = response.data
    } else {
      currentContest.value = null
    }
  } catch (error) {
    console.error('加载当前竞赛失败:', error)
    currentContest.value = null
  }
}

const loadRecentRankings = async () => {
  try {
    const response = await getRecentContestRankings()
    // 确保返回的数据是数组
    if (Array.isArray(response.data)) {
      recentRankings.value = response.data
    } else {
      recentRankings.value = []
    }
  } catch (error) {
    console.error('加载最近排行榜失败:', error)
    recentRankings.value = []
  }
}

const loadHistoryContests = async () => {
  try {
    // 这里可以调用获取历史竞赛的API
    // 暂时使用空数组
    historyContests.value = []
  } catch (error) {
    console.error('加载历史竞赛失败:', error)
  }
}

// 刷新竞赛数据
const refreshContests = async () => {
  try {
    loading.value = true
    await Promise.all([
      loadUpcomingContests(),
      loadCurrentContest(),
      loadRecentRankings()
    ])
  } catch (error) {
    console.error('刷新竞赛数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 加入竞赛
const handleJoinContest = async (contestId: number) => {
  try {
    loading.value = true
    await joinContestAPI(contestId)
    // 重新加载数据
    await loadUpcomingContests()
    await loadCurrentContest()
  } catch (error) {
    console.error('加入竞赛失败:', error)
    alert('加入竞赛失败，请重试')
  } finally {
    loading.value = false
  }
}

// 格式化时间
const formatDateTime = (dateString: string | undefined) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const formatDate = (dateString: string | undefined) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
}

const getTimeUntilStart = (startTimeString: string) => {
  const now = new Date()
  const startTime = new Date(startTimeString)
  const diff = startTime.getTime() - now.getTime()
  
  if (diff <= 0) return '已开始'
  
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  const hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60))
  
  if (days > 0) {
    return `${days}天${hours}小时`
  } else if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 加入竞赛的别名方法
const joinContest = handleJoinContest

onMounted(async () => {
  loading.value = true
  try {
    await Promise.all([
      loadUpcomingContests(),
      loadCurrentContest(),
      loadRecentRankings(),
      loadHistoryContests()
    ])
  } catch (error) {
    console.error('加载数据失败:', error)
  } finally {
    loading.value = false
  }
})
</script>
